#include "musiclist.h"
#include<QMimeDatabase>

MusicList::MusicList()
{

}

iterator MusicList::begin()
{
    return musicList.begin();
}

iterator MusicList::end()
{
    return musicList.end();
}

void MusicList::addMusicByUrl(const QList<QUrl> &urls)
{


    for(auto musicUrl:urls)
    {
#if 0
        auto it = begin();
        for(; it!=end();++it)
        {
            if(it->getMusicUrl()==musicUrl)
            {
                break;
            }
        }
        if(it!=end())
        {
            continue;
        }
#endif
        QString musicPath=musicUrl.toLocalFile();
        if(musicPaths.contains(musicPath))
            continue;
        musicPaths.insert(musicPath);



        //添加进来的文件有可能不是歌曲文件，所以需要进行筛选
        QMimeDatabase db;
        QMimeType mime=db.mimeTypeForFile(musicUrl.toLocalFile());
        if(mime.name() == "audio/mpeg" || mime.name() == "audio/flac"||mime.name()=="audio/wav")
        {
            Music music(musicUrl);
            musicList.push_back(musicUrl);
        }
    }
}

iterator MusicList::findMusicById(const QString &musicId)
{
    for(iterator it = begin(); it != end(); ++it)
    {
        if(it->getMusicId() == musicId)
        {
            return it;
        }
    }
    return end();
}

void MusicList::writeToDB()
{
    for(auto music:musicList)
    {
        music.insertMusicToDB();
    }
}

void MusicList::readFromDB()
{
    QString sql("SELECT musicId, musicName, SingerName,albumName,\
                duration,musicUrl,isLIke,isHistory FROM musicInfo");
                QSqlQuery query;
            if(!query.exec(sql))
    {
        qDebug()<<"数据库查询失败";
        return;
    }
    while (query.next())
    {
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setSingerName(query.value(2).toString());
        music.setAlbumName(query.value(3).toString());
        music.setDuration(query.value(4).toLongLong());
        music.setMusicUrl(query.value(5).toString());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());

        musicList.push_back(music);
    }
}

